/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package paquetevistas.ventas;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import jxl.Sheet;
import jxl.Workbook;
import static paquetevistas.configuracion.CargaMasivaMaquinas.mycontroladorconfiguracion;

/**
 *
 * @author Karina
 */
public class CargaMasivaClientes extends javax.swing.JInternalFrame {

    /**
     * Creates new form CargaMasivaClientes
     */
    public CargaMasivaClientes() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setTitle("Carga Masiva de Clientes");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccione el archivo"));

        jLabel1.setText("Archivo");

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/search.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/save.png"))); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Buscar");

        jLabel3.setText("Guardar");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel3))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(14, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(22, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(21, 21, 21))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        jTextField1.setEditable(false);
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JFileChooser file = new JFileChooser();
        int opcion = file.showOpenDialog(this);
        if (opcion == JFileChooser.APPROVE_OPTION) {
            this.jTextField1.setText(file.getSelectedFile().getPath());
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // SI NO HAY RUTA
        if ("".equals(jTextField1.getText())) {
            JOptionPane.showMessageDialog(this, "Ruta de archivo no especificada.");
            return;
        }
        
         if (JOptionPane.showConfirmDialog(this,
                "¿Está seguro de agregar los Clientes desde " + jTextField1.getText() + "?", "Carga Masiva de Clientes", JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION){
            //Empiezo a reccorre
            int fila = 0;
            int col = 0;
            
            try{
                Workbook archivoExcel = Workbook.getWorkbook(new File(jTextField1.getText()));
                
                Sheet hoja = archivoExcel.getSheet(0);
                int numColumnas = hoja.getColumns();
                int numFilas = hoja.getRows();
                
                List<modelos.Cliente> clientes = new ArrayList<modelos.Cliente>();
                List<modelos.Cliente> clientesexistentes = new ArrayList<modelos.Cliente>();
                int existencia;
                int estadoid;
                for (fila = 2; fila < numFilas; fila++) {
                    existencia=0;
                    col=0;
                    
                    modelos.Cliente cli = new modelos.Cliente();
                    String razonsocial, direccion, direccionentrega, correo, nombrecontacto, dnicontacto;
                    String ruc;
                    int telefono, telefonocontacto;
                    
                    razonsocial =hoja.getCell(col++, fila).getContents();
                    ruc = hoja.getCell(col++, fila).getContents();
                    direccion = hoja.getCell(col++, fila).getContents();
                    direccionentrega = hoja.getCell(col++, fila).getContents();
                    telefono = Integer.parseInt(hoja.getCell(col++, fila).getContents());
                    nombrecontacto= hoja.getCell(col++, fila).getContents();
                    dnicontacto = hoja.getCell(col++, fila).getContents();
                    correo =  hoja.getCell(col++, fila).getContents();
                    telefonocontacto = Integer.parseInt(hoja.getCell(col++, fila).getContents());
                    
                    cli.setRazonsocial(razonsocial);
                    cli.setDireccion(direccion);
                    cli.setTelefono(telefono);
                    cli.setNombrecontacto(nombrecontacto);
                    cli.setCorreo(correo);
                    cli.setDnicontacto(dnicontacto);
                    cli.setDireccion1(direccion);
                    cli.setRuc(Long.parseLong(ruc));
                    cli.setTelefonocontacto(telefonocontacto);
                    cli.setEstado(1);
                    
                    existencia = mycontroladorconfiguracion.verificaexistenciacliente(Long.parseLong(ruc));
                    if (existencia == 1) {
                        clientesexistentes.add(cli);
                    } else {
                        clientes.add(cli);
                    }
                }
                
                    if(clientes.size() > 0 && clientesexistentes.size()==0){
                        mycontroladorconfiguracion.guardaListacliente(clientes);
                        lbj.LBJ.Login.escritorio.clientes.refresh();
                        JOptionPane.showMessageDialog(this, "Se agregaron los clientes exitosamente.");
                        //lbj.LBJ.Login.escritorio.clientes.re;
                        this.dispose();
                    } else if (clientes.size() == 0 && clientesexistentes.size() > 0) {
                        JOptionPane.showMessageDialog(this, "Los clientes que intenta guardar ya existen.");
                        this.dispose();
                    } else if(clientes.size() > 0 && clientesexistentes.size()>0){
                        mycontroladorconfiguracion.guardaListacliente(clientes);
                        lbj.LBJ.Login.escritorio.clientes.refresh();
                        JOptionPane.showMessageDialog(this, "Se agregaron las clientes nuevas exitosamente. Algunos ya existian");
                        //lbj.LBJ.Login.escritorio.maquina.refreshMaquinasTable();
                        this.dispose();
                    } else if (clientes.size() == 0 && clientesexistentes.size() > 0) {
                    JOptionPane.showMessageDialog(this, "El archivo que intenta cargar esta vacio.");
                    this.dispose();
                    }
                
            }catch(Exception ioe){
                ioe.printStackTrace();
                JOptionPane.showMessageDialog(null, "Error: En el Archivo, en la Fila " + (fila + 1) + " y Columna " + col);
            }
            
         }
    }//GEN-LAST:event_jButton2ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
